import storage from './storage'
import { generateUrl, createOption, getRequest } from './request'
import config from '../config'
import { DeviceEventEmitter } from 'react-native'

// 获取username
export function getUsername() {
  return storage.load({key: 'username'})
}
// 获取password
export function getPassword() {
    return storage.load({key: 'pass'})
  }
// 获取headImgUrl
export function getHeadImgUrl() {
    return storage.load({key: 'headImgurl'})
  }
// 设置username
export function setUsername(data) {
  storage.save({
    key: 'username',
    data: data
  }).then(() => {
    DeviceEventEmitter.emit('loginEvent')
  })
}
// 设置password
export function setPassword(data) {
    storage.save({
      key: 'pass',
      data: data
    }).then(() => {
      DeviceEventEmitter.emit('loginEvent')
    })
  }
  // 设置headImgUrl
export function setHeadImgUrl(data) {
    storage.save({
      key: 'headImgurl',
      data: data
    }).then(() => {
      DeviceEventEmitter.emit('loginEvent')
    })
  }
// 删除username
export function removeUsername() {
  storage.remove({
    key: 'username'
  })
}
// 删除pass
export function removePassword() {
    storage.remove({
      key: 'pass'
    })
  }
  // 删除headImgurl
export function removeHeadImgUrl() {
    storage.remove({
      key: 'headImgurl'
    })
  }
/**
*  检查token失效
*  return 0可用,1过期,2失效
*/
export function checkTokenExpire(token) {
  let currentTime = new Date().getTime();
  let expireTime = new Date(token.expire.replace(/-/g, '/')).getTime()
  let invalidTime = new Date(token.invalid.replace(/-/g, '/')).getTime()
  // 已失效
  if(currentTime > invalidTime) {
    removeToken()
    return 2
  }
  // 过期之前多少毫秒可刷新
  let refreshTime = config.token.refreshSecond * 1000
  // 已过期
  if( currentTime > (expireTime - refreshTime) ) {
    return 1
  }

  return 0
}

// 刷新token
export function refreshToken(token) {
  let option = {
    method: 'post',
    path: 'auth/token/refresh'
  }

  let url = generateUrl(option.path)
  url += '?token=' + token
  let requestOption = createOption(option, url).requestOption

  return new Promise(function(resolve, reject) {
    getRequest(requestOption, url).then(response => {
      setToken(response)
      resolve(response.token)
    })
  })
}
